import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:flutter_map_animations/flutter_map_animations.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:latlong2/latlong.dart';
import 'package:situation/app/page/home_index/widgets/MyMark.dart';
import 'package:situation/app/router/router_name.dart';
import 'package:situation/data/bus/intercom_bus.dart';
import 'package:situation/data/channel/intercom_channel.dart';
import 'package:situation/data/database/sql_provider.dart';
import 'package:situation/data/enum/map_tool_enum.dart';
import 'package:situation/data/request/base_request.dart';
import 'package:situation/data/store/auth_store.dart';
import 'package:situation/domain/db/user_latlon_domain.dart';
import 'package:situation/shared/shared.dart';
import 'package:situation/shared/util/util_mk.dart';
import 'package:situation/widgets/map/tool/area_measure_tool.dart';
import 'package:situation/widgets/map/tool/distance_measure_tool.dart';
import 'package:situation/widgets/map/tool/map_line_draw.dart';
import 'package:situation/widgets/map/tool/map_point_draw.dart';
import 'package:situation/widgets/map/tool/map_polygon_draw.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';

import 'state.dart';

class HomeIndexController extends GetxController
    with GetTickerProviderStateMixin {
  final HomeIndexState state = HomeIndexState();
  late AnimatedMapController animatedMapController = AnimatedMapController(
    vsync: this,
    duration: const Duration(milliseconds: 500),
    curve: Curves.easeInOut,
    cancelPreviousAnimations: true, // Default to false
  );

  TextEditingController mapToolNameController = TextEditingController();

  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();

    _getLocation();

    // 5秒执行一次
    Timer.periodic(const Duration(seconds: 5), (timer) {
      _getRounderPoints();
    });
  }

  // 获取周边队员
  void _getRounderPoints() async {
    var device = UtilSp.getString(AppConstant.DEVICE_POSITION)!;
    if (device == "") {
      return;
    }
    var lat = device.split(",")[0];
    var lon = device.split(",")[1];

    if (!AuthStore.to.isLogin) {
      return;
    }

    var d = await BaseRequest.getTeamUserPoints({
      "lat": lat,
      "lon": lon,
      "radius": 100,
    });
    state.aroundPoints = d['data'];
    state.aroundPoints = state.aroundPoints.toList();
  }

  // 地图工具
  /**
   * 绘制点
   */
  void drawPoint() {
    SmartDialog.showToast('进入点绘制');
    state.toolEvent = MapToolEventEnum.drawPoint;
  }

  /**
   * 绘制线
   */
  void drawLine() {
    SmartDialog.showToast('进入线绘制');

    state.toolEvent = MapToolEventEnum.drawLine;
    MapLineDraw.startNewLine();
  }

  /**
   * 绘制面
   */
  void drawArea() {
    SmartDialog.showToast('进入面绘制');
    state.toolEvent = MapToolEventEnum.drawArea;
    MapPolygonDraw.startNewPolygon();
  }

  /**
   * 计算距离
   */
  void sumDistance() {
    SmartDialog.showToast("距离计算");
    state.toolEvent = MapToolEventEnum.sumDistance;
  }

  /**
   * 计算面积
   */
  void sumArea() {
    SmartDialog.showToast("面积计算");
    state.toolEvent = MapToolEventEnum.sumArea;
  }

  /**
   * 绘制结束
   */
  void drawEnd() {
    SmartDialog.showToast("停止绘制");
    state.toolEvent = MapToolEventEnum.none;
  }

  void drawClear() {
    MapPointDraw.removeAll();
    MapLineDraw.removeAll();
    MapPolygonDraw.removeAll();
    state.myMarkList = [];
    state.checkedIds = [];
    state.toolEvent == MapToolEventEnum.none;
  }

  // 地图点击
  void mapOnTap(TapPosition tapPosition, LatLng point) {
    if (state.toolEvent == MapToolEventEnum.drawPoint) {
      // 画点
      MapPointDraw.addPoint(point);
    }
    if (state.toolEvent == MapToolEventEnum.drawLine) {
      MapLineDraw.addPoint(point);
    }
    if (state.toolEvent == MapToolEventEnum.drawArea) {
      MapPolygonDraw.addPoint(point);
    }

    if (state.toolEvent == MapToolEventEnum.sumDistance) {
      DistanceMeasureTool.addPoint(point);
    }

    if (state.toolEvent == MapToolEventEnum.sumArea) {
      AreaMeasureTool.addPoint(point);
    }
  }

  void _getLocation() async {
    //获取当前的权限
    bool isGranted = await UtilPermission.requestLocationPermission();

    if(!isGranted){
      return;
    }
    IntercomChannel.to.getLocation();


    IntercomBus.to.getBus().on<IntercomEvent>().listen((event) {
      if (event.event == IntercomChannel.to.LOCATION_EVENT) {
        var d;
        if(event.data.runtimeType == String){
          d = jsonDecode(event.data);
        }else {
          d = event.data;
        }
        var lat = d['lat'];
        var lon = d['lon'];
        final newPoint = LatLng(lat,lon);
        animatedMapController.mapController.move(newPoint, 17);
      }
    });
  }

  void changeTab(int value) {
    switch (value) {
      case 1:
        Get.toNamed(RouterName.communicationConcatList);
        break;
      case 2:
        Get.toNamed(RouterName.publishIndex);
        break;
      case 3:
        Get.toNamed(RouterName.userIndex);
        break;
    }
  }

  void toChat(e) {
    Get.toNamed(RouterName.communicationChat, arguments: e);
  }

  // 但
  void onSinglePointSave(LatLng latlng) {
    pointSaveToDb("point", [latlng]);
  }

  onLineSave(List<LatLng> latlngList) {
    pointSaveToDb("line", latlngList);
  }

  onAreaSave(List<LatLng> latlngList) {
    pointSaveToDb("area", latlngList);
  }

  pointSaveToDb(type, latlngList) {
    var latlonList = [];

    for (var e in latlngList) {
      latlonList.add({"lat": e.latitude, "lon": e.longitude});
    }

    mapToolNameController.text = "";
    state.toolEvent = MapToolEventEnum.none;
    showGeneralDialog(
      context: Get.context!,
      pageBuilder: (
        BuildContext buildContext,
        Animation<double> animation,
        Animation<double> secondaryAnimation,
      ) {
        return TDInputDialog(
          textEditingController: mapToolNameController,
          title: "请输入名称",
          showCloseButton: true,
          rightBtn: TDDialogButtonOptions(
            title: '保存',
            action: () {
              SqlProvider.instance.insert(UserLatlonDomain.tableName, {
                "name": mapToolNameController.text,
                "type": type,
                "list": jsonEncode(latlonList),
              });
              SmartDialog.showToast("保存成功");
              Get.back();
            },
          ),
        );
      },
    );
  }

  resetEventTool() {
    if (state.toolEvent == MapToolEventEnum.sumDistance) {
      SmartDialog.showToast("已退出距离计算");
    }
    if (state.toolEvent == MapToolEventEnum.sumArea) {
      SmartDialog.showToast("已退出面积计算");
    }
    if (state.toolEvent == MapToolEventEnum.drawPoint) {
      SmartDialog.showToast("已退出点标记");
    }
    state.toolEvent = MapToolEventEnum.none;
  }

  void switchMap() {
    if (state.mapType == 'yxt') {
      SmartDialog.showToast("切换至电子图");
      state.mapType = 'dzt';
    } else {
      SmartDialog.showToast("切换至影像图");
      state.mapType = 'yxt';
    }
  }

  handleMyMark() async {
    Navigator.of(Get.context!).push(
      TDSlidePopupRoute(
        modalBarrierColor: TDTheme.of(Get.context).fontGyColor2,
        slideTransitionFrom: SlideTransitionFrom.bottom,
        builder: (context) {
          return TDPopupBottomDisplayPanel(
            title: '我标记的',
            closeClick: () {
              Navigator.maybePop(context);
            },
            child: Container(
              height: 480,
              child: Mymark(
                handleChange: handleMyMarkChange,
                checkedIds: state.checkedIds,
              ),
            ),
          );
        },
      ),
    );
  }

  handleMyMarkChange(List<UserLatlonDomain> p1) {
    // 修改checkedIds ;
    state.checkedIds = p1.map((e) => e.id).toList();
    state.myMarkList = p1;
  }
}
